package com.example.littleken.dialogtext;

import android.app.DatePickerDialog;
import android.icu.util.Calendar;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Date;

public class DataActivity extends AppCompatActivity {
    private Button btn_setTime;
    private TextView textView;
    private int year,month,day;
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data);
        getdata();

        String time = year+"年"+(month+1)+"月"+day+"日";

        textView = (TextView) findViewById(R.id.tv_time);
        textView.setText(time);
        btn_setTime = (Button) findViewById(R.id.setTime);
        btn_setTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog my_datePickerDialog = new DatePickerDialog(DataActivity.this,Datalistener,year,month,day);
                my_datePickerDialog.show();
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void getdata() {
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(calendar.MONTH);
        day = calendar.get(calendar.DAY_OF_MONTH);
       // Toast.makeText(DataActivity.this,year+""+month+""+day, Toast.LENGTH_SHORT).show();
    }

    private DatePickerDialog.OnDateSetListener Datalistener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int y, int m, int d) {
            Date dateset = new Date(y,m,d);
            Date datenow = new Date(year,month,day);
            if(dateset.after(datenow)){
                Toast.makeText(DataActivity.this,"设置日期有误", Toast.LENGTH_SHORT).show();
                return;
            }else {
                year = y;
                month = m;
                day = d;
                String time = year + "年" + (month + 1) + "月" + day + "日";
                Log.e("TAG", time);
                updateDate(time);
            }
        }
        private void updateDate(String time){
            textView.setText(time);
        }
    };
}
